Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       

import numpy as np
import tensorflow as tf
from keras.utils import np_utils
from glob import glob
%load_ext tensorboard


# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
import random
import matplotlib as mpl
%matplotlib inline                               
mpl.rcParams['figure.dpi']= 150

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
fig, ax = plt.subplots(1, 5, figsize=(15,15))

for i in range(5):
    # load color (BGR) image
    import random

    img_index = random.randint(0, len(human_files)-1)
    
    img = cv2.imread(human_files[img_index])
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)

    # print number of faces detected in the image
    print('Number of faces detected:', len(faces))

    # get bounding box for each detected face
    for (x,y,w,h) in faces:
        # add bounding box to color image
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.subplot(1,5, i+1)
    plt.imshow(cv_rgb)
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
from tqdm import tqdm

# calculate percentage of detected human faces in human_files
results = []
for file in (human_files_short):
    results.append(face_detector(file))
np_results_humans = np.array(results)
print("detected faces in human files: {}".format(np.sum(np_results_humans)))

# calculate percentage of detected human faces in dog_files
results = []
for file in (dog_files_short):
    results.append(face_detector(file))
np_results_dogs = np.array(results)
print("detected faces in dog files: {}".format(np.sum(np_results_dogs)))
detected faces in human files: 98
detected faces in dog files: 12

So there are $98$ percent detected faces in human files and $12$ percent detected faces in dog_files.

Let's now take a look at the specific files the algorithm misclassified:

In [6]:
# show false positives dogs
fig, ax = plt.subplots(3, 4, figsize=(15,10))
false_positives_idx = np.where(np_results_dogs)[0]
for i, idx in enumerate(false_positives_idx):
    # load color (BGR) image
    import random

    
    img = cv2.imread(dog_files_short[idx])
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)

    # print number of faces detected in the image
    print('Number of faces detected:', len(faces))

    # get bounding box for each detected face
    color = (0, 0, 255) 
    for (x,y,w,h) in faces:
        # add bounding box to color image
        cv2.rectangle(img,(x,y),(x+w,y+h),color,2)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.subplot(3,4, i+1)
    plt.imshow(cv_rgb)
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
In [7]:
# show false negatives humans
fig, ax = plt.subplots(1, 2, figsize=(7,4))
false_negatives_idx = np.where(np_results_humans == False)[0]
for i, idx in enumerate(false_negatives_idx):
    # load color (BGR) image
    import random

    
    img = cv2.imread(human_files_short[idx])
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)

    # print number of faces detected in the image
    print('Number of faces detected:', len(faces))

    # get bounding box for each detected face
    color = (0, 0, 255) 
    for (x,y,w,h) in faces:
        # add bounding box to color image
        cv2.rectangle(img,(x,y),(x+w,y+h),color,2)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.subplot(1,2, i+1)
    plt.imshow(cv_rgb)
Number of faces detected: 0
Number of faces detected: 0

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: Generally, I would think that it would be a plausible requirement to only accept ...

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [8]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [9]:
from tensorflow.keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [10]:
from tensorflow.keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [11]:
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [12]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [13]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_files_short = human_files[:100]
dog_files_short = train_files[:100]

# calculate percentage of detected human faces in human_files
results = []
for file in (human_files_short):
    results.append(dog_detector(file))
np_human_results = np.array(results)
print("percentage of detected dogs in human files: {} %".format(np.sum(np_human_results)))

# calculate percentage of detected human faces in dog_files
results = []
for file in (dog_files_short):
    results.append(dog_detector(file))
np_dog_results = np.array(results)
print("percentage of detected dogs in dog files: {} %".format(np.sum(np_dog_results)))
percentage of detected dogs in human files: 1 %
percentage of detected dogs in dog files: 100 %

Obviously, the classifier correctly detected dog content in each of the dog images. Let's now take look on the human image, which was potentially misclassified:

In [14]:
np.where(np_human_results)
Out[14]:
(array([6]),)
In [15]:
img = cv2.imread(human_files[6])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(gray)
Out[15]:
<matplotlib.image.AxesImage at 0x7f4d5009a518>

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [16]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [00:57<00:00, 115.82it/s]
100%|██████████| 835/835 [00:06<00:00, 127.60it/s]
100%|██████████| 836/836 [00:06<00:00, 129.57it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: **To do**

In [54]:
from tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from tensorflow.keras.layers import Dropout, Flatten, Dense
from tensorflow.keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, kernel_size=2, activation='relu', padding='valid', input_shape=(224,224,3)))
model.add(MaxPooling2D(pool_size=(2,2), padding='valid'))
model.add(Conv2D(32, kernel_size=2, activation='relu', padding='valid'))
model.add(MaxPooling2D(pool_size=(2,2), padding='valid'))
model.add(Conv2D(64, kernel_size=2, activation='relu', padding='valid'))
model.add(MaxPooling2D(pool_size=(2,2), padding='valid'))
model.add(Conv2D(128, kernel_size=2, activation='relu', padding='valid'))
model.add(MaxPooling2D(pool_size=(2,2), padding='valid'))
model.add(Conv2D(256, kernel_size=2, activation='relu', padding='valid'))
model.add(MaxPooling2D(pool_size=(2,2), padding='valid'))
model.add(GlobalAveragePooling2D())
model.add(Dropout(0.4))
model.add(Dense(units=133, activation='softmax'))
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_5 (Conv2D)            (None, 223, 223, 16)      208       
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 110, 110, 32)      2080      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 55, 55, 32)        0         
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 54, 54, 64)        8256      
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 27, 27, 64)        0         
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 26, 26, 128)       32896     
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 13, 13, 128)       0         
_________________________________________________________________
conv2d_9 (Conv2D)            (None, 12, 12, 256)       131328    
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 6, 6, 256)         0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 256)               0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               34181     
=================================================================
Total params: 208,949
Trainable params: 208,949
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [55]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [56]:
from tensorflow.keras.callbacks import ModelCheckpoint  
import datetime

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 30

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

history = model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer, tensorboard_callback], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8701 - accuracy: 0.0093
Epoch 00001: val_loss improved from inf to 4.80423, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.8696 - accuracy: 0.0094 - val_loss: 4.8042 - val_accuracy: 0.0132
Epoch 2/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.7693 - accuracy: 0.0201
Epoch 00002: val_loss improved from 4.80423 to 4.71054, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.7692 - accuracy: 0.0201 - val_loss: 4.7105 - val_accuracy: 0.0251
Epoch 3/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.6854 - accuracy: 0.0251
Epoch 00003: val_loss improved from 4.71054 to 4.69778, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.6850 - accuracy: 0.0251 - val_loss: 4.6978 - val_accuracy: 0.0263
Epoch 4/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.5951 - accuracy: 0.0360
Epoch 00004: val_loss improved from 4.69778 to 4.64287, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.5954 - accuracy: 0.0361 - val_loss: 4.6429 - val_accuracy: 0.0347
Epoch 5/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.4959 - accuracy: 0.0440
Epoch 00005: val_loss improved from 4.64287 to 4.48036, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.4967 - accuracy: 0.0439 - val_loss: 4.4804 - val_accuracy: 0.0515
Epoch 6/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.3867 - accuracy: 0.0492
Epoch 00006: val_loss improved from 4.48036 to 4.36727, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.3873 - accuracy: 0.0493 - val_loss: 4.3673 - val_accuracy: 0.0635
Epoch 7/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.2860 - accuracy: 0.0649
Epoch 00007: val_loss improved from 4.36727 to 4.34335, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.2859 - accuracy: 0.0650 - val_loss: 4.3433 - val_accuracy: 0.0467
Epoch 8/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.1944 - accuracy: 0.0701
Epoch 00008: val_loss improved from 4.34335 to 4.23209, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.1941 - accuracy: 0.0701 - val_loss: 4.2321 - val_accuracy: 0.0683
Epoch 9/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.1008 - accuracy: 0.0829
Epoch 00009: val_loss improved from 4.23209 to 4.09856, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.1003 - accuracy: 0.0829 - val_loss: 4.0986 - val_accuracy: 0.0671
Epoch 10/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.0394 - accuracy: 0.0886
Epoch 00010: val_loss did not improve from 4.09856
6680/6680 [==============================] - 13s 2ms/sample - loss: 4.0396 - accuracy: 0.0889 - val_loss: 4.1973 - val_accuracy: 0.0766
Epoch 11/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.9681 - accuracy: 0.1012
Epoch 00011: val_loss did not improve from 4.09856
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.9674 - accuracy: 0.1015 - val_loss: 4.2348 - val_accuracy: 0.0898
Epoch 12/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.9045 - accuracy: 0.1029
Epoch 00012: val_loss improved from 4.09856 to 3.96422, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.9040 - accuracy: 0.1030 - val_loss: 3.9642 - val_accuracy: 0.0850
Epoch 13/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.8479 - accuracy: 0.1113
Epoch 00013: val_loss improved from 3.96422 to 3.88653, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.8473 - accuracy: 0.1111 - val_loss: 3.8865 - val_accuracy: 0.0994
Epoch 14/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7992 - accuracy: 0.1182
Epoch 00014: val_loss did not improve from 3.88653
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.7981 - accuracy: 0.1184 - val_loss: 3.9316 - val_accuracy: 0.0970
Epoch 15/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7492 - accuracy: 0.1239
Epoch 00015: val_loss did not improve from 3.88653
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.7497 - accuracy: 0.1240 - val_loss: 4.0720 - val_accuracy: 0.0886
Epoch 16/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.6885 - accuracy: 0.1368
Epoch 00016: val_loss improved from 3.88653 to 3.74757, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.6872 - accuracy: 0.1368 - val_loss: 3.7476 - val_accuracy: 0.1138
Epoch 17/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.6368 - accuracy: 0.1384
Epoch 00017: val_loss did not improve from 3.74757
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.6367 - accuracy: 0.1385 - val_loss: 3.7485 - val_accuracy: 0.1257
Epoch 18/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5964 - accuracy: 0.1468
Epoch 00018: val_loss did not improve from 3.74757
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.5964 - accuracy: 0.1469 - val_loss: 3.8858 - val_accuracy: 0.1102
Epoch 19/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5315 - accuracy: 0.1620
Epoch 00019: val_loss improved from 3.74757 to 3.68228, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.5319 - accuracy: 0.1618 - val_loss: 3.6823 - val_accuracy: 0.1341
Epoch 20/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4888 - accuracy: 0.1592
Epoch 00020: val_loss improved from 3.68228 to 3.58658, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.4880 - accuracy: 0.1594 - val_loss: 3.5866 - val_accuracy: 0.1509
Epoch 21/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4630 - accuracy: 0.1649
Epoch 00021: val_loss did not improve from 3.58658
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.4629 - accuracy: 0.1650 - val_loss: 3.6077 - val_accuracy: 0.1485
Epoch 22/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4194 - accuracy: 0.1740
Epoch 00022: val_loss improved from 3.58658 to 3.56309, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.4211 - accuracy: 0.1738 - val_loss: 3.5631 - val_accuracy: 0.1509
Epoch 23/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.3696 - accuracy: 0.1761
Epoch 00023: val_loss did not improve from 3.56309
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.3700 - accuracy: 0.1759 - val_loss: 3.5852 - val_accuracy: 0.1545
Epoch 24/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.3532 - accuracy: 0.1875
Epoch 00024: val_loss did not improve from 3.56309
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.3523 - accuracy: 0.1877 - val_loss: 3.7271 - val_accuracy: 0.1461
Epoch 25/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.2976 - accuracy: 0.1977
Epoch 00025: val_loss improved from 3.56309 to 3.48645, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.2967 - accuracy: 0.1981 - val_loss: 3.4864 - val_accuracy: 0.1796
Epoch 26/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.2687 - accuracy: 0.2080
Epoch 00026: val_loss did not improve from 3.48645
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.2693 - accuracy: 0.2078 - val_loss: 3.6263 - val_accuracy: 0.1629
Epoch 27/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.2255 - accuracy: 0.2071
Epoch 00027: val_loss improved from 3.48645 to 3.48228, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.2269 - accuracy: 0.2070 - val_loss: 3.4823 - val_accuracy: 0.1713
Epoch 28/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.1900 - accuracy: 0.2230
Epoch 00028: val_loss improved from 3.48228 to 3.40374, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.1906 - accuracy: 0.2226 - val_loss: 3.4037 - val_accuracy: 0.2012
Epoch 29/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.1431 - accuracy: 0.2249
Epoch 00029: val_loss did not improve from 3.40374
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.1419 - accuracy: 0.2250 - val_loss: 3.4188 - val_accuracy: 0.2012
Epoch 30/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.1157 - accuracy: 0.2270
Epoch 00030: val_loss did not improve from 3.40374
6680/6680 [==============================] - 13s 2ms/sample - loss: 3.1138 - accuracy: 0.2272 - val_loss: 3.5653 - val_accuracy: 0.1892
In [59]:
plt.style.use('seaborn')
figure, ax = plt.subplots(1,1, figsize=(8,4))
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('CNN from scratch - model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
_ = plt.xticks(range(0, epochs))
In [60]:
# save history
import pandas as pd
df_history = pd.DataFrame(history.history)
df_history.to_csv('history/history1.csv', index=False)
In [61]:
pd.read_csv('history/history1.csv')
Out[61]:
loss accuracy val_loss val_accuracy
0 4.869640 0.009431 4.804227 0.013174
1 4.769219 0.020060 4.710540 0.025150
2 4.684958 0.025150 4.697782 0.026347
3 4.595375 0.036078 4.642872 0.034731
4 4.496707 0.043862 4.480358 0.051497
5 4.387310 0.049251 4.367274 0.063473
6 4.285881 0.064970 4.343350 0.046707
7 4.194150 0.070060 4.232094 0.068263
8 4.100293 0.082934 4.098563 0.067066
9 4.039567 0.088922 4.197308 0.076647
10 3.967399 0.101497 4.234783 0.089820
11 3.903978 0.102994 3.964222 0.085030
12 3.847323 0.111078 3.886531 0.099401
13 3.798140 0.118413 3.931609 0.097006
14 3.749705 0.123952 4.071972 0.088623
15 3.687228 0.136826 3.747573 0.113772
16 3.636673 0.138473 3.748539 0.125749
17 3.596410 0.146856 3.885812 0.110180
18 3.531918 0.161826 3.682279 0.134132
19 3.488004 0.159431 3.586579 0.150898
20 3.462948 0.164970 3.607653 0.148503
21 3.421143 0.173802 3.563088 0.150898
22 3.370033 0.175898 3.585173 0.154491
23 3.352296 0.187725 3.727141 0.146108
24 3.296666 0.198054 3.486450 0.179641
25 3.269349 0.207784 3.626346 0.162874
26 3.226947 0.207036 3.482284 0.171257
27 3.190554 0.222605 3.403743 0.201198
28 3.141940 0.225000 3.418826 0.201198
29 3.113798 0.227246 3.565305 0.189222

Load the Model with the Best Validation Loss

In [62]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [63]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 16.5072%

AlexNet

In [66]:
import tensorflow.keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization
import numpy as np
# new model
AlexNet_model = Sequential()


# Conv2D C1
AlexNet_model.add(Conv2D(filters=96, input_shape=(224,224,3), kernel_size=(11,11), strides=(4,4), padding='valid', activation='relu'))
# Max Pooling S2
AlexNet_model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid'))

# Conv2D C3
AlexNet_model.add(Conv2D(filters=256, kernel_size=(5,5), strides=(1,1), padding='same', activation='relu'))
# Max Pooling S4
AlexNet_model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid'))


# Conv2D C5
AlexNet_model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))

# Conv2D C6
AlexNet_model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))

# Conv2D C7
AlexNet_model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))
#AlexNet_model.add(BatchNormalization())

# Max Pooling S8
AlexNet_model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid'))
#AlexNet_model.add(BatchNormalization())

# Flatten for FC
AlexNet_model.add(Flatten())



# FC F9
AlexNet_model.add(Dense(4096, input_shape=(224*224*3,), activation='relu'))
# Dropout
AlexNet_model.add(Dropout(0.5))


# FC F9
AlexNet_model.add(Dense(4096,activation='relu'))
# Dropout
AlexNet_model.add(Dropout(0.5))



# Output
AlexNet_model.add(Dense(133, activation='softmax'))

AlexNet_model.summary()
Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_20 (Conv2D)           (None, 54, 54, 96)        34944     
_________________________________________________________________
max_pooling2d_16 (MaxPooling (None, 26, 26, 96)        0         
_________________________________________________________________
conv2d_21 (Conv2D)           (None, 26, 26, 256)       614656    
_________________________________________________________________
max_pooling2d_17 (MaxPooling (None, 12, 12, 256)       0         
_________________________________________________________________
conv2d_22 (Conv2D)           (None, 12, 12, 384)       885120    
_________________________________________________________________
conv2d_23 (Conv2D)           (None, 12, 12, 384)       1327488   
_________________________________________________________________
conv2d_24 (Conv2D)           (None, 12, 12, 256)       884992    
_________________________________________________________________
max_pooling2d_18 (MaxPooling (None, 5, 5, 256)         0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 6400)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 4096)              26218496  
_________________________________________________________________
dropout_3 (Dropout)          (None, 4096)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 4096)              16781312  
_________________________________________________________________
dropout_4 (Dropout)          (None, 4096)              0         
_________________________________________________________________
dense_7 (Dense)              (None, 133)               544901    
=================================================================
Total params: 47,291,909
Trainable params: 47,291,909
Non-trainable params: 0
_________________________________________________________________
In [67]:
# Compile AlexNet
import tensorflow.keras
AlexNet_model.compile(loss=tensorflow.keras.losses.categorical_crossentropy, optimizer='SGD', metrics=['accuracy'])
In [68]:
# test AlexNet
from tensorflow.keras.callbacks import ModelCheckpoint  
epochs = 30

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch_alexnet2.hdf5', 
                               verbose=1, save_best_only=False)

AlexNet_history = AlexNet_model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8885 - accuracy: 0.0071
Epoch 00001: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 24s 4ms/sample - loss: 4.8886 - accuracy: 0.0070 - val_loss: 4.8789 - val_accuracy: 0.0120
Epoch 2/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8774 - accuracy: 0.0084
Epoch 00002: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8774 - accuracy: 0.0084 - val_loss: 4.8691 - val_accuracy: 0.0108
Epoch 3/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8711 - accuracy: 0.0089
Epoch 00003: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8710 - accuracy: 0.0090 - val_loss: 4.8613 - val_accuracy: 0.0108
Epoch 4/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8654 - accuracy: 0.0098
Epoch 00004: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8651 - accuracy: 0.0097 - val_loss: 4.8567 - val_accuracy: 0.0108
Epoch 5/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8577 - accuracy: 0.0111
Epoch 00005: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8576 - accuracy: 0.0111 - val_loss: 4.8484 - val_accuracy: 0.0132
Epoch 6/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8415 - accuracy: 0.0119
Epoch 00006: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8417 - accuracy: 0.0120 - val_loss: 4.8284 - val_accuracy: 0.0144
Epoch 7/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8103 - accuracy: 0.0147
Epoch 00007: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.8104 - accuracy: 0.0147 - val_loss: 4.7791 - val_accuracy: 0.0156
Epoch 8/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.7698 - accuracy: 0.0228
Epoch 00008: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.7699 - accuracy: 0.0228 - val_loss: 4.7231 - val_accuracy: 0.0287
Epoch 9/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.6876 - accuracy: 0.0272
Epoch 00009: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.6871 - accuracy: 0.0271 - val_loss: 4.6192 - val_accuracy: 0.0311
Epoch 10/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.5914 - accuracy: 0.0323
Epoch 00010: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.5914 - accuracy: 0.0322 - val_loss: 4.6826 - val_accuracy: 0.0323
Epoch 11/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.4896 - accuracy: 0.0419
Epoch 00011: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.4885 - accuracy: 0.0418 - val_loss: 4.4900 - val_accuracy: 0.0443
Epoch 12/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.4070 - accuracy: 0.0461
Epoch 00012: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.4070 - accuracy: 0.0460 - val_loss: 4.3753 - val_accuracy: 0.0515
Epoch 13/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.3272 - accuracy: 0.0526
Epoch 00013: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.3272 - accuracy: 0.0525 - val_loss: 4.3580 - val_accuracy: 0.0515
Epoch 14/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.2601 - accuracy: 0.0625
Epoch 00014: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.2590 - accuracy: 0.0624 - val_loss: 4.2214 - val_accuracy: 0.0611
Epoch 15/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.1796 - accuracy: 0.0664
Epoch 00015: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.1799 - accuracy: 0.0662 - val_loss: 4.1872 - val_accuracy: 0.0683
Epoch 16/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.0986 - accuracy: 0.0740
Epoch 00016: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.0985 - accuracy: 0.0743 - val_loss: 4.1651 - val_accuracy: 0.0671
Epoch 17/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.0235 - accuracy: 0.0845
Epoch 00017: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 4.0242 - accuracy: 0.0844 - val_loss: 4.0692 - val_accuracy: 0.0743
Epoch 18/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.9583 - accuracy: 0.0962
Epoch 00018: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.9584 - accuracy: 0.0963 - val_loss: 4.0630 - val_accuracy: 0.0743
Epoch 19/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.8749 - accuracy: 0.1023
Epoch 00019: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.8749 - accuracy: 0.1024 - val_loss: 3.9818 - val_accuracy: 0.0970
Epoch 20/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.8047 - accuracy: 0.1156
Epoch 00020: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.8050 - accuracy: 0.1156 - val_loss: 3.9714 - val_accuracy: 0.0946
Epoch 21/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7386 - accuracy: 0.1263
Epoch 00021: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.7385 - accuracy: 0.1260 - val_loss: 3.9752 - val_accuracy: 0.0982
Epoch 22/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.6634 - accuracy: 0.1347
Epoch 00022: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.6631 - accuracy: 0.1347 - val_loss: 3.9516 - val_accuracy: 0.0994
Epoch 23/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5520 - accuracy: 0.1514
Epoch 00023: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.5523 - accuracy: 0.1512 - val_loss: 3.8917 - val_accuracy: 0.1018
Epoch 24/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4542 - accuracy: 0.1644
Epoch 00024: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.4519 - accuracy: 0.1650 - val_loss: 3.8611 - val_accuracy: 0.1018
Epoch 25/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.3519 - accuracy: 0.1877
Epoch 00025: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.3521 - accuracy: 0.1874 - val_loss: 4.0114 - val_accuracy: 0.0994
Epoch 26/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.1994 - accuracy: 0.2182
Epoch 00026: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.2002 - accuracy: 0.2180 - val_loss: 3.8805 - val_accuracy: 0.1329
Epoch 27/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.0674 - accuracy: 0.2419
Epoch 00027: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 3.0671 - accuracy: 0.2419 - val_loss: 3.8405 - val_accuracy: 0.1293
Epoch 28/30
6660/6680 [============================>.] - ETA: 0s - loss: 2.8991 - accuracy: 0.2748
Epoch 00028: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 2.8996 - accuracy: 0.2749 - val_loss: 3.8102 - val_accuracy: 0.1329
Epoch 29/30
6660/6680 [============================>.] - ETA: 0s - loss: 2.7501 - accuracy: 0.3039
Epoch 00029: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 2.7504 - accuracy: 0.3034 - val_loss: 3.9508 - val_accuracy: 0.1437
Epoch 30/30
6660/6680 [============================>.] - ETA: 0s - loss: 2.5437 - accuracy: 0.3420
Epoch 00030: saving model to saved_models/weights.best.from_scratch_alexnet2.hdf5
6680/6680 [==============================] - 23s 3ms/sample - loss: 2.5441 - accuracy: 0.3422 - val_loss: 3.9129 - val_accuracy: 0.1437
In [76]:
plt.figure(figsize=(8,4))
plt.plot(AlexNet_history.history['accuracy'])
plt.plot(AlexNet_history.history['val_accuracy'])
plt.title('AlexNet - model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
_ = plt.xticks(range(0, epochs))
In [75]:
AlexNet_model.load_weights('saved_models/weights.best.from_scratch_alexnet2.hdf5')

# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(AlexNet_model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 15.5502%
In [71]:
#Train with data augmentation
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import clone_model

AlexNet_data_augmentation_model = clone_model(AlexNet_model)

AlexNet_data_augmentation_model.compile(optimizer='SGD', loss='categorical_crossentropy', metrics=['accuracy'])

batch_size = 32
epochs = 30

AlexNet_data_augmentation_checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5', 
                               verbose=1, save_best_only=True)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        brightness_range=[0.9,1.1],
        width_shift_range=0.05,
        height_shift_range=0.05,
        horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        'dogImages/train',
        target_size=(224, 224),
        batch_size=batch_size,
        class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
        'dogImages/valid',
        target_size=(224, 224),
        batch_size=batch_size,
        class_mode='categorical')
AlexNet_data_augmentation_history = AlexNet_data_augmentation_model.fit(
        train_generator,
        steps_per_epoch=train_files.size//batch_size,
        epochs=epochs,
        validation_data=validation_generator,
        validation_steps=valid_files.size//batch_size, callbacks=[AlexNet_data_augmentation_checkpointer])
Found 6680 images belonging to 133 classes.
Found 835 images belonging to 133 classes.
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to  
  ['...']
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to  
  ['...']
Train for 208 steps, validate for 26 steps
Epoch 1/30
207/208 [============================>.] - ETA: 0s - loss: 4.8879 - accuracy: 0.0091
Epoch 00001: val_loss improved from inf to 4.88123, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 143s 687ms/step - loss: 4.8879 - accuracy: 0.0090 - val_loss: 4.8812 - val_accuracy: 0.0108
Epoch 2/30
207/208 [============================>.] - ETA: 0s - loss: 4.8821 - accuracy: 0.0107
Epoch 00002: val_loss improved from 4.88123 to 4.86999, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 684ms/step - loss: 4.8822 - accuracy: 0.0107 - val_loss: 4.8700 - val_accuracy: 0.0108
Epoch 3/30
207/208 [============================>.] - ETA: 0s - loss: 4.8748 - accuracy: 0.0076
Epoch 00003: val_loss improved from 4.86999 to 4.86609, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.8747 - accuracy: 0.0075 - val_loss: 4.8661 - val_accuracy: 0.0168
Epoch 4/30
207/208 [============================>.] - ETA: 0s - loss: 4.8692 - accuracy: 0.0089
Epoch 00004: val_loss improved from 4.86609 to 4.85975, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 684ms/step - loss: 4.8693 - accuracy: 0.0089 - val_loss: 4.8597 - val_accuracy: 0.0108
Epoch 5/30
207/208 [============================>.] - ETA: 0s - loss: 4.8651 - accuracy: 0.0107
Epoch 00005: val_loss improved from 4.85975 to 4.85687, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 684ms/step - loss: 4.8651 - accuracy: 0.0108 - val_loss: 4.8569 - val_accuracy: 0.0108
Epoch 6/30
207/208 [============================>.] - ETA: 0s - loss: 4.8574 - accuracy: 0.0119
Epoch 00006: val_loss improved from 4.85687 to 4.85074, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 680ms/step - loss: 4.8572 - accuracy: 0.0119 - val_loss: 4.8507 - val_accuracy: 0.0144
Epoch 7/30
207/208 [============================>.] - ETA: 0s - loss: 4.8550 - accuracy: 0.0135
Epoch 00007: val_loss improved from 4.85074 to 4.84867, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.8550 - accuracy: 0.0134 - val_loss: 4.8487 - val_accuracy: 0.0204
Epoch 8/30
207/208 [============================>.] - ETA: 0s - loss: 4.8415 - accuracy: 0.0165
Epoch 00008: val_loss improved from 4.84867 to 4.82356, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 682ms/step - loss: 4.8415 - accuracy: 0.0164 - val_loss: 4.8236 - val_accuracy: 0.0168
Epoch 9/30
207/208 [============================>.] - ETA: 0s - loss: 4.8164 - accuracy: 0.0209
Epoch 00009: val_loss improved from 4.82356 to 4.79887, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.8168 - accuracy: 0.0209 - val_loss: 4.7989 - val_accuracy: 0.0288
Epoch 10/30
207/208 [============================>.] - ETA: 0s - loss: 4.7644 - accuracy: 0.0222
Epoch 00010: val_loss improved from 4.79887 to 4.72556, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 679ms/step - loss: 4.7652 - accuracy: 0.0221 - val_loss: 4.7256 - val_accuracy: 0.0300
Epoch 11/30
207/208 [============================>.] - ETA: 0s - loss: 4.7115 - accuracy: 0.0248
Epoch 00011: val_loss did not improve from 4.72556
208/208 [==============================] - 141s 676ms/step - loss: 4.7111 - accuracy: 0.0247 - val_loss: 4.7527 - val_accuracy: 0.0132
Epoch 12/30
207/208 [============================>.] - ETA: 0s - loss: 4.6552 - accuracy: 0.0275
Epoch 00012: val_loss improved from 4.72556 to 4.62411, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 679ms/step - loss: 4.6554 - accuracy: 0.0275 - val_loss: 4.6241 - val_accuracy: 0.0361
Epoch 13/30
207/208 [============================>.] - ETA: 0s - loss: 4.5989 - accuracy: 0.0308
Epoch 00013: val_loss improved from 4.62411 to 4.55679, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.5994 - accuracy: 0.0310 - val_loss: 4.5568 - val_accuracy: 0.0421
Epoch 14/30
207/208 [============================>.] - ETA: 0s - loss: 4.5270 - accuracy: 0.0360
Epoch 00014: val_loss improved from 4.55679 to 4.47142, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 678ms/step - loss: 4.5275 - accuracy: 0.0360 - val_loss: 4.4714 - val_accuracy: 0.0421
Epoch 15/30
207/208 [============================>.] - ETA: 0s - loss: 4.4752 - accuracy: 0.0413
Epoch 00015: val_loss improved from 4.47142 to 4.39551, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 678ms/step - loss: 4.4748 - accuracy: 0.0415 - val_loss: 4.3955 - val_accuracy: 0.0397
Epoch 16/30
207/208 [============================>.] - ETA: 0s - loss: 4.4049 - accuracy: 0.0482
Epoch 00016: val_loss improved from 4.39551 to 4.36452, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.4060 - accuracy: 0.0483 - val_loss: 4.3645 - val_accuracy: 0.0493
Epoch 17/30
207/208 [============================>.] - ETA: 0s - loss: 4.3450 - accuracy: 0.0473
Epoch 00017: val_loss improved from 4.36452 to 4.31299, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 143s 689ms/step - loss: 4.3453 - accuracy: 0.0472 - val_loss: 4.3130 - val_accuracy: 0.0517
Epoch 18/30
207/208 [============================>.] - ETA: 0s - loss: 4.3131 - accuracy: 0.0538
Epoch 00018: val_loss improved from 4.31299 to 4.28323, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 678ms/step - loss: 4.3121 - accuracy: 0.0537 - val_loss: 4.2832 - val_accuracy: 0.0565
Epoch 19/30
207/208 [============================>.] - ETA: 0s - loss: 4.2694 - accuracy: 0.0565
Epoch 00019: val_loss improved from 4.28323 to 4.22871, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 681ms/step - loss: 4.2701 - accuracy: 0.0566 - val_loss: 4.2287 - val_accuracy: 0.0649
Epoch 20/30
207/208 [============================>.] - ETA: 0s - loss: 4.2160 - accuracy: 0.0623
Epoch 00020: val_loss improved from 4.22871 to 4.19879, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 677ms/step - loss: 4.2151 - accuracy: 0.0623 - val_loss: 4.1988 - val_accuracy: 0.0721
Epoch 21/30
207/208 [============================>.] - ETA: 0s - loss: 4.1735 - accuracy: 0.0656
Epoch 00021: val_loss improved from 4.19879 to 4.15136, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 682ms/step - loss: 4.1736 - accuracy: 0.0656 - val_loss: 4.1514 - val_accuracy: 0.0697
Epoch 22/30
207/208 [============================>.] - ETA: 0s - loss: 4.1405 - accuracy: 0.0689
Epoch 00022: val_loss did not improve from 4.15136
208/208 [==============================] - 140s 672ms/step - loss: 4.1405 - accuracy: 0.0689 - val_loss: 4.1698 - val_accuracy: 0.0649
Epoch 23/30
207/208 [============================>.] - ETA: 0s - loss: 4.0937 - accuracy: 0.0768
Epoch 00023: val_loss improved from 4.15136 to 4.14421, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 678ms/step - loss: 4.0943 - accuracy: 0.0767 - val_loss: 4.1442 - val_accuracy: 0.0769
Epoch 24/30
207/208 [============================>.] - ETA: 0s - loss: 4.0656 - accuracy: 0.0786
Epoch 00024: val_loss improved from 4.14421 to 4.07246, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 143s 687ms/step - loss: 4.0664 - accuracy: 0.0785 - val_loss: 4.0725 - val_accuracy: 0.0817
Epoch 25/30
207/208 [============================>.] - ETA: 0s - loss: 4.0213 - accuracy: 0.0801
Epoch 00025: val_loss did not improve from 4.07246
208/208 [==============================] - 140s 673ms/step - loss: 4.0218 - accuracy: 0.0805 - val_loss: 4.1526 - val_accuracy: 0.0745
Epoch 26/30
207/208 [============================>.] - ETA: 0s - loss: 3.9833 - accuracy: 0.0893
Epoch 00026: val_loss improved from 4.07246 to 4.02742, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 683ms/step - loss: 3.9836 - accuracy: 0.0895 - val_loss: 4.0274 - val_accuracy: 0.0925
Epoch 27/30
207/208 [============================>.] - ETA: 0s - loss: 3.9418 - accuracy: 0.0924
Epoch 00027: val_loss improved from 4.02742 to 4.00023, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 142s 684ms/step - loss: 3.9427 - accuracy: 0.0925 - val_loss: 4.0002 - val_accuracy: 0.0853
Epoch 28/30
207/208 [============================>.] - ETA: 0s - loss: 3.8884 - accuracy: 0.1005
Epoch 00028: val_loss did not improve from 4.00023
208/208 [==============================] - 140s 674ms/step - loss: 3.8906 - accuracy: 0.1002 - val_loss: 4.0358 - val_accuracy: 0.0950
Epoch 29/30
207/208 [============================>.] - ETA: 0s - loss: 3.8649 - accuracy: 0.1028
Epoch 00029: val_loss improved from 4.00023 to 3.91083, saving model to saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5
208/208 [==============================] - 141s 678ms/step - loss: 3.8648 - accuracy: 0.1027 - val_loss: 3.9108 - val_accuracy: 0.1034
Epoch 30/30
207/208 [============================>.] - ETA: 0s - loss: 3.8221 - accuracy: 0.1120
Epoch 00030: val_loss did not improve from 3.91083
208/208 [==============================] - 140s 672ms/step - loss: 3.8230 - accuracy: 0.1118 - val_loss: 3.9367 - val_accuracy: 0.1070
In [77]:
plt.figure(figsize=(8,4))
plt.plot(AlexNet_data_augmentation_history.history['accuracy'])
plt.plot(AlexNet_data_augmentation_history.history['val_accuracy'])
plt.title('AlexNet with data augmentation - model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
_ = plt.xticks(range(0, epochs))
In [74]:
AlexNet_data_augmentation_model.load_weights('saved_models/weights.best.from_scratch_alexnet_data_augmentation.hdf5')

# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(AlexNet_data_augmentation_model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 10.8852%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [16]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
In [17]:
train_targets.shape
Out[17]:
(6680, 133)

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [22]:
from keras.models import Sequential
from keras.layers import GlobalAveragePooling2D, Dense
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [23]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [25]:
from keras.callbacks import ModelCheckpoint  

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', verbose=1, save_best_only=True)


VGG16_history = VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0200 - accuracy: 0.9949 - val_loss: 2.2514 - val_accuracy: 0.7389

Epoch 00001: val_loss improved from inf to 2.25140, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/20
6680/6680 [==============================] - 1s 181us/step - loss: 0.0167 - accuracy: 0.9955 - val_loss: 2.1313 - val_accuracy: 0.7437

Epoch 00002: val_loss improved from 2.25140 to 2.13129, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0148 - accuracy: 0.9960 - val_loss: 2.2842 - val_accuracy: 0.7281

Epoch 00003: val_loss did not improve from 2.13129
Epoch 4/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0130 - accuracy: 0.9963 - val_loss: 2.2754 - val_accuracy: 0.7401

Epoch 00004: val_loss did not improve from 2.13129
Epoch 5/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0175 - accuracy: 0.9955 - val_loss: 2.2155 - val_accuracy: 0.7425

Epoch 00005: val_loss did not improve from 2.13129
Epoch 6/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0134 - accuracy: 0.9961 - val_loss: 2.3952 - val_accuracy: 0.7437

Epoch 00006: val_loss did not improve from 2.13129
Epoch 7/20
6680/6680 [==============================] - 1s 184us/step - loss: 0.0100 - accuracy: 0.9973 - val_loss: 2.3161 - val_accuracy: 0.7521

Epoch 00007: val_loss did not improve from 2.13129
Epoch 8/20
6680/6680 [==============================] - 1s 184us/step - loss: 0.0122 - accuracy: 0.9975 - val_loss: 2.4353 - val_accuracy: 0.7473

Epoch 00008: val_loss did not improve from 2.13129
Epoch 9/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0129 - accuracy: 0.9973 - val_loss: 2.3526 - val_accuracy: 0.7437

Epoch 00009: val_loss did not improve from 2.13129
Epoch 10/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0127 - accuracy: 0.9973 - val_loss: 2.3862 - val_accuracy: 0.7437

Epoch 00010: val_loss did not improve from 2.13129
Epoch 11/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0097 - accuracy: 0.9978 - val_loss: 2.5240 - val_accuracy: 0.7473

Epoch 00011: val_loss did not improve from 2.13129
Epoch 12/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0099 - accuracy: 0.9976 - val_loss: 2.5883 - val_accuracy: 0.7437

Epoch 00012: val_loss did not improve from 2.13129
Epoch 13/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0062 - accuracy: 0.9975 - val_loss: 2.6352 - val_accuracy: 0.7461

Epoch 00013: val_loss did not improve from 2.13129
Epoch 14/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0098 - accuracy: 0.9976 - val_loss: 2.5472 - val_accuracy: 0.7437

Epoch 00014: val_loss did not improve from 2.13129
Epoch 15/20
6680/6680 [==============================] - 1s 184us/step - loss: 0.0094 - accuracy: 0.9979 - val_loss: 2.5805 - val_accuracy: 0.7449

Epoch 00015: val_loss did not improve from 2.13129
Epoch 16/20
6680/6680 [==============================] - 1s 185us/step - loss: 0.0071 - accuracy: 0.9984 - val_loss: 2.6644 - val_accuracy: 0.7473

Epoch 00016: val_loss did not improve from 2.13129
Epoch 17/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0111 - accuracy: 0.9981 - val_loss: 2.7088 - val_accuracy: 0.7497

Epoch 00017: val_loss did not improve from 2.13129
Epoch 18/20
6680/6680 [==============================] - 1s 183us/step - loss: 0.0115 - accuracy: 0.9981 - val_loss: 2.6117 - val_accuracy: 0.7485

Epoch 00018: val_loss did not improve from 2.13129
Epoch 19/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0085 - accuracy: 0.9984 - val_loss: 2.6676 - val_accuracy: 0.7473

Epoch 00019: val_loss did not improve from 2.13129
Epoch 20/20
6680/6680 [==============================] - 1s 182us/step - loss: 0.0076 - accuracy: 0.9984 - val_loss: 2.5957 - val_accuracy: 0.7473

Epoch 00020: val_loss did not improve from 2.13129
In [27]:
epochs = 20
plt.style.use('seaborn')
plt.figure(figsize=(8,4))
plt.plot(VGG16_history.history['accuracy'])
plt.plot(VGG16_history.history['val_accuracy'])
plt.title('VGG16 Transfer Learning - model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
_ = plt.xticks(range(0, epochs))

Load the Model with the Best Validation Loss

In [28]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [29]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 75.1196%

Predict Dog Breed with the Model

In [30]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [31]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_InceptionV3 = bottleneck_features['train']
valid_InceptionV3 = bottleneck_features['valid']
test_InceptionV3 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

In [74]:
from keras.layers import Dropout, BatchNormalization
InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
InceptionV3_model.add(Dropout(0.5))
InceptionV3_model.add(BatchNormalization())
InceptionV3_model.add(Dense(133, activation='softmax'))

InceptionV3_model.summary()
Model: "sequential_11"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_11  (None, 2048)              0         
_________________________________________________________________
dropout_17 (Dropout)         (None, 2048)              0         
_________________________________________________________________
batch_normalization_1 (Batch (None, 2048)              8192      
_________________________________________________________________
dense_18 (Dense)             (None, 133)               272517    
=================================================================
Total params: 280,709
Trainable params: 276,613
Non-trainable params: 4,096
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [75]:
### Compile the model.
InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='SGD', metrics=['accuracy'], learning_rate=)

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [76]:
### Train the model.
from keras.callbacks import ModelCheckpoint  

epochs = 30

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_history = InceptionV3_model.fit(train_InceptionV3, train_targets, 
          validation_data=(valid_InceptionV3, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/30
6680/6680 [==============================] - 2s 329us/step - loss: 1.5661 - accuracy: 0.6201 - val_loss: 0.5428 - val_accuracy: 0.8156

Epoch 00001: val_loss improved from inf to 0.54282, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 2/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.5997 - accuracy: 0.8169 - val_loss: 0.5399 - val_accuracy: 0.8443

Epoch 00002: val_loss improved from 0.54282 to 0.53991, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 3/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.4456 - accuracy: 0.8620 - val_loss: 0.5382 - val_accuracy: 0.8443

Epoch 00003: val_loss improved from 0.53991 to 0.53823, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 4/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.3667 - accuracy: 0.8813 - val_loss: 0.5648 - val_accuracy: 0.8371

Epoch 00004: val_loss did not improve from 0.53823
Epoch 5/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.3257 - accuracy: 0.8936 - val_loss: 0.6010 - val_accuracy: 0.8431

Epoch 00005: val_loss did not improve from 0.53823
Epoch 6/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.2889 - accuracy: 0.9013 - val_loss: 0.5926 - val_accuracy: 0.8491

Epoch 00006: val_loss did not improve from 0.53823
Epoch 7/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.2520 - accuracy: 0.9147 - val_loss: 0.6014 - val_accuracy: 0.8527

Epoch 00007: val_loss did not improve from 0.53823
Epoch 8/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.2318 - accuracy: 0.9210 - val_loss: 0.6097 - val_accuracy: 0.8515

Epoch 00008: val_loss did not improve from 0.53823
Epoch 9/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.2087 - accuracy: 0.9286 - val_loss: 0.6415 - val_accuracy: 0.8431

Epoch 00009: val_loss did not improve from 0.53823
Epoch 10/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.2331 - accuracy: 0.9235 - val_loss: 0.6529 - val_accuracy: 0.8503

Epoch 00010: val_loss did not improve from 0.53823
Epoch 11/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1891 - accuracy: 0.9361 - val_loss: 0.6994 - val_accuracy: 0.8407

Epoch 00011: val_loss did not improve from 0.53823
Epoch 12/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.2020 - accuracy: 0.9350 - val_loss: 0.6707 - val_accuracy: 0.8419

Epoch 00012: val_loss did not improve from 0.53823
Epoch 13/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1943 - accuracy: 0.9380 - val_loss: 0.6959 - val_accuracy: 0.8539

Epoch 00013: val_loss did not improve from 0.53823
Epoch 14/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.1713 - accuracy: 0.9404 - val_loss: 0.7313 - val_accuracy: 0.8479

Epoch 00014: val_loss did not improve from 0.53823
Epoch 15/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.1867 - accuracy: 0.9377 - val_loss: 0.7859 - val_accuracy: 0.8347

Epoch 00015: val_loss did not improve from 0.53823
Epoch 16/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1579 - accuracy: 0.9439 - val_loss: 0.7370 - val_accuracy: 0.8479

Epoch 00016: val_loss did not improve from 0.53823
Epoch 17/30
6680/6680 [==============================] - 2s 290us/step - loss: 0.1702 - accuracy: 0.9442 - val_loss: 0.7534 - val_accuracy: 0.8407

Epoch 00017: val_loss did not improve from 0.53823
Epoch 18/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1754 - accuracy: 0.9440 - val_loss: 0.7894 - val_accuracy: 0.8383

Epoch 00018: val_loss did not improve from 0.53823
Epoch 19/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1741 - accuracy: 0.9442 - val_loss: 0.7734 - val_accuracy: 0.8491

Epoch 00019: val_loss did not improve from 0.53823
Epoch 20/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.1671 - accuracy: 0.9484 - val_loss: 0.8440 - val_accuracy: 0.8491

Epoch 00020: val_loss did not improve from 0.53823
Epoch 21/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.1559 - accuracy: 0.9494 - val_loss: 0.8158 - val_accuracy: 0.8479

Epoch 00021: val_loss did not improve from 0.53823
Epoch 22/30
6680/6680 [==============================] - 2s 288us/step - loss: 0.1521 - accuracy: 0.9516 - val_loss: 0.7995 - val_accuracy: 0.8611

Epoch 00022: val_loss did not improve from 0.53823
Epoch 23/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1528 - accuracy: 0.9510 - val_loss: 0.8618 - val_accuracy: 0.8539

Epoch 00023: val_loss did not improve from 0.53823
Epoch 24/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.1597 - accuracy: 0.9493 - val_loss: 0.8223 - val_accuracy: 0.8635

Epoch 00024: val_loss did not improve from 0.53823
Epoch 25/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1509 - accuracy: 0.9504 - val_loss: 0.8431 - val_accuracy: 0.8635

Epoch 00025: val_loss did not improve from 0.53823
Epoch 26/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1597 - accuracy: 0.9539 - val_loss: 0.8650 - val_accuracy: 0.8539

Epoch 00026: val_loss did not improve from 0.53823
Epoch 27/30
6680/6680 [==============================] - 2s 289us/step - loss: 0.1461 - accuracy: 0.9539 - val_loss: 0.8376 - val_accuracy: 0.8587

Epoch 00027: val_loss did not improve from 0.53823
Epoch 28/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1529 - accuracy: 0.9540 - val_loss: 0.8958 - val_accuracy: 0.8407

Epoch 00028: val_loss did not improve from 0.53823
Epoch 29/30
6680/6680 [==============================] - 2s 287us/step - loss: 0.1220 - accuracy: 0.9618 - val_loss: 0.8305 - val_accuracy: 0.8563

Epoch 00029: val_loss did not improve from 0.53823
Epoch 30/30
6680/6680 [==============================] - 2s 286us/step - loss: 0.1358 - accuracy: 0.9566 - val_loss: 0.8349 - val_accuracy: 0.8527

Epoch 00030: val_loss did not improve from 0.53823
In [78]:
plt.style.use('seaborn')
plt.figure(figsize=(8,4))
plt.plot(InceptionV3_history.history['accuracy'])
plt.plot(InceptionV3_history.history['val_accuracy'])
plt.title('InceptionV3 Transfer Learning - model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
_ = plt.xticks(range(0, epochs))

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [79]:
### TODO: Load the model weights with the best validation loss.
InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [80]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]

# report test accuracy
test_accuracy = 100*np.sum(np.array(InceptionV3_predictions)==np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 83.3732%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [81]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *

def InceptionV3_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_InceptionV3(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = InceptionV3_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [89]:
InceptionV3_predict_breed('images/bud-spencer-bart.jpg')
Out[89]:
'Border_terrier'
In [150]:
# show false positives dogs
#fig, ax = plt.subplots(3, 4, figsize=(15,10))
mpl.rcParams.update(mpl.rcParamsDefault)

%matplotlib inline

def show_breed_images(str_breed):
    fig, ax = plt.subplots(1, 4, figsize=(16,8))
    img_idx =  np.flatnonzero(np.core.defchararray.find(train_files,str_breed)!=-1)
    for i, idx in enumerate(np.random.choice(img_idx, 4)):
        plt.subplot(1,4, i+1)
        img = cv2.imread(train_files[idx])
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

Function to show 4 random images of a specific dog breed

In [157]:
# function to show 4 random images of a specific dog breed
mpl.rcParams.update(mpl.rcParamsDefault)

%matplotlib inline

def show_breed_images(str_breed):
    """
    shows 4 images of specific dog breed.
    INPUT:
        str_breed: name of the breed
    
    """
    fig, ax = plt.subplots(1, 4, figsize=(16,8))
    img_idx =  np.flatnonzero(np.core.defchararray.find(train_files,str_breed)!=-1)
    for i, idx in enumerate(np.random.choice(img_idx, 4)):
        plt.subplot(1,4, i+1)
        img = cv2.imread(train_files[idx])
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)
In [158]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
def evaluate_image(img_path):
    """
    If a dog is detected in the image, it will provide an estimate of the dog's breed.
    If a human is detected, it will provide an estimate of the dog breed that is most resembling.
    INPUT:
        img_path: path of image input
    
    """
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(img)
    dog_breed = InceptionV3_predict_breed(img_path)
    text = "Hmmm, I can't see any humans or dogs in this picture, but it reminds me a bit of a " + dog_breed + "."
    
    if (dog_detector(img_path)):
        text = "I'm pretty sure it's a dog. I think it could be a " + dog_breed + "."
    elif (face_detector(img_path)):
        text = "You're definitely human, but if you were a dog you could be a " + dog_breed + "."
    
    print(text)
    show_breed_images(dog_breed)

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

In [159]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
evaluate_image('images/snoop-dogg.jpg')
evaluate_image()
You're definitely human, but if you were a dog you could be a Smooth_fox_terrier.
In [134]:
test_image('images/wladimir_putin.jpg')
You're definitely human, but if you were a dog you could be a Cardigan_welsh_corgi
In [160]:
evaluate_image('images/man_as_dalmatian.jpg')
I'm pretty sure it's a dog. I think it could be a Dalmatian.
In [136]:
test_image('images/Curly-coated_retriever_03896.jpg')
I'm pretty sure it's a dog. I think it could be a Curly-coated_retriever
In [153]:
test_image('images/Mops_oct09_cropped2.jpg')
I'm pretty sure it's a dog. I think it could be a Chinese_shar-pei.
In [156]:
test_image('images/Doberman-2-645mk062111.jpg')
I'm pretty sure it's a dog. I think it could be a Doberman_pinscher.
In [141]:
test_image('images/Pug-On-White-01.jpg')
I'm pretty sure it's a dog. I think it could be a Bulldog.
In [142]:
test_image('images/daftpunk_dafunk.jpg')
I'm pretty sure it's a dog. I think it could be a Dachshund.
In [152]:
test_image('images/trump.jpg')
You're definitely human, but if you were a dog you could be a Irish_water_spaniel.
In [147]:
test_image('images/alf.jpg')
Hmm, I can't see any humans or dogs in this picture, but it reminds me a bit of a Nova_scotia_duck_tolling_retriever.
In [ ]: